package de.herberlin.server.common;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

/**
 * New Configuration Service uses the java.util.prefs.Preferences Api;
 * @author hans joachim herbertz
 * created 28.12.2003
 */
public abstract class Configuration {
	/**
	 * Preference name package
	 */
	public static final Class PREF_CLASS =
		de.herberlin.server.common.AbstractServer.class;
	private static Preferences preferences = null;
	private static Logger logger = Logger.getLogger(PREF_CLASS.getName());

	/**
	 * Gets the application root preferences.
	 * @return
	 */
	public static Preferences getPrefs() {
		if (preferences == null) {
			if (ConfigConstants.USE_CONFIG_FILE) {
				try {
					Preferences.importPreferences(
						new FileInputStream(ConfigConstants.CONFIG_FILE));
				} catch (Throwable e) {
					logger.info("Preference import fails: " + e);
				}
			}
			preferences = Preferences.userNodeForPackage(PREF_CLASS);
			logger.fine("Root preferences set up: " + preferences);
		}
		return preferences;
	}

	/**
	 * Stores the preferences to file.
	 * @throws Exception
	 */
	public static void store() throws Exception {
		if (ConfigConstants.USE_CONFIG_FILE) {
			try {
				getPrefs().exportSubtree(
					new FileOutputStream(ConfigConstants.CONFIG_FILE));
			} catch (Throwable e) {
				logger.warning("Preference storage fails: " + e);
				throw new Exception(e);
			}
		}
	}

	/**
	 * Gets the mimeType node of the application preferences.
	 * @return
	 */
	public static Preferences getMimeTypes() {
		String name = "mimeTypes";
		Preferences prefs = getPrefs();
		try {
			if (!prefs.nodeExists(name)) {
				// TODO have more mimetypes here
				Preferences p = prefs.node(name);
				p.put("jpeg", "image/jpeg");
				p.put("php", "text/html");
				p.put("gif", "image/gif");
				p.put("txt", "text/plain");
				p.put("html", "text/html");
				p.put("htm", "text/html");
				p.put("shtml", "text/html");
				p.put("shtm", "text/html");
				p.put("css", "text/css");
				p.put("htm", "text/html");
				p.put("png", "image/png");
				p.put("jpg", "image/jpeg");
				p.put("jpe", "image/jpeg");
				p.put("zip", "application/zip");

			}
		} catch (BackingStoreException e) {
			logger.severe(
				"Failed adding default mimetype to preferences: " + e);
		}
		return prefs.node(name);
	}
	/**
	 * Returns the extensions node of the application preferences.
	 * @return
	 */
	public static Preferences getExtensions() {
		String name = "extension";
		return getPrefs().node(name);

	}
	/**
	 * Returns the Alias Directory node of the application preferences.
	 * @return
	 */
	public static Preferences getAliasDirectories() {
		String name = "aliasDirectories";
		return getPrefs().node(name);
	}

}
